//
//  JdunionHelper.m
//  jdunion_plugin
//
//  Created by Franky Lee on 2022/9/14.
//

#import "JdunionHelper.h"
#import <JDSDK/JDKeplerSDK.h>

static JdunionHelper *jdunionHelper = nil;

@implementation JdunionHelper

+ (instancetype)sharedInstance {
    return [[self alloc] init];
}

- (instancetype)init {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        jdunionHelper = [super init];
    });
    return jdunionHelper;
}

- (void)initJdUnion:(NSString *)version :(FlutterResult)fResult {
    [[KeplerApiManager sharedKPService]asyncInitSdk:@"76c965923ecd408cb8bbf4af07799b01" secretKey:@"c5fbfa9964b646c7add4b6e14c198ccd" sucessCallback:^(){
        NSLog(@"京东SDK初始化成功--");
    }failedCallback:^(NSError *error){
        NSLog(@"京东SDK初始化失败--%@", error.domain);
    }];
}

/**
 *  通过URL打开任意商品页面
 */
- (void)openJDAppByUrl:(NSString *)url :(FlutterResult)fResult {
    NSDictionary *userInfo = @{@"subUnionId":@""};
    NSLog(@"openJDAppByUrl：%@", url);
    [[KeplerApiManager sharedKPService]openKeplerPageWithURL:url userInfo:userInfo successCallback:^{
        fResult(0);
    } failedCallback:^(NSInteger code, NSString * _Nonnull url) {
        NSLog(@"打开京东APP失败：%ld", code);
        NSLog(@"打开京东APP失败：%@", url);
        if (code == 422) {
            NSMutableDictionary *body = @{@"code":[NSNumber numberWithInt: code] , @"message": @"未安装京东App"}.mutableCopy;
            fResult(body);
        }
    }];
}

/**
 *  通过URL打开京喜APP
 */
- (void)openJXAppByUrl:(NSString *)url :(FlutterResult)fResult {
    NSDictionary *userInfo = @{@"subUnionId":@""};
    [[KeplerApiManager sharedKPService]openJXPageWithUrl:url userInfo:userInfo
                                                 success:^{
        fResult(0);
    } failure:^(NSInteger code, NSString * _Nonnull url) {
        NSLog(@"打开京喜APP失败：%ld", code);
        NSLog(@"打开京喜APP失败：%@", url);
        if (code == 422) {
            NSMutableDictionary *body = @{@"code":[NSNumber numberWithInt: code], @"message": @"未安装京喜App"}.mutableCopy;
            fResult(body);
        }
    }];
    
}

@end
